package com.liusiqi.framework.beans.factory.xml;

import com.liusiqi.framework.beans.BeanDefinition;
import com.liusiqi.framework.beans.MutablePropertyValues;
import com.liusiqi.framework.beans.PropertyValue;
import com.liusiqi.framework.beans.factory.support.BeanDefinitionReader;
import com.liusiqi.framework.beans.factory.support.BeanDefinitionRegistry;
import com.liusiqi.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author: sql
 * @date: 2024/2/22
 * @Description:XML文件解析实现类
 * @version: 1.0
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //使用Dom4j解析XML
        SAXReader reader = new SAXReader();
        InputStream inputStream = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document document = reader.read(inputStream);
        Element rootElement = document.getRootElement();
        parseBean(rootElement);
    }

    private void parseBean(Element rootElement) {
        List<Element> elements = rootElement.elements();
        //遍历每个bean标签，获取id、className属性及property标签属性
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String className = element.attributeValue("class");
            List<Element> propertys = element.elements("property");
            //数据封装
            MutablePropertyValues propertyValues = new MutablePropertyValues();
            for (Element property : propertys) {
                String name = property.attributeValue("name");
                String ref = property.attributeValue("ref");
                String value = property.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, value, ref);
                propertyValues.addPropertyValue(propertyValue);
            }
            BeanDefinition beanDefinition = new BeanDefinition(id, className, propertyValues);
            //将beanDefinition注册到注册表
            registry.registerBeanDefinition(id, beanDefinition);
            System.out.println(beanDefinition);
        }
    }

    public static void main(String[] args) throws Exception{
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader();
        reader.loadBeanDefinitions("bean.xml");
    }
}
